package com.rainy.sso.server.interceptor;

import com.rainy.sso.client.entity.Application;
import com.rainy.sso.client.service.ApplicationService;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author liuqin on 2017/12/23
 */
public class SsoLoginInterceptor implements HandlerInterceptor{

    @Resource
    private ApplicationService applicationService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String domain = request.getRemoteHost();
        String appId = request.getParameter("appId");
        String callback = request.getParameter("callback");
        String callbackHost = "http://"+callback.replace("http://","").substring(0,callback.indexOf("/"));
        boolean switchs = true;
        if (domain.equals(callbackHost) || switchs) {
            Application application = applicationService.queryApplicationByAppId(appId);
            if (!application.getDomain().equals(domain) || switchs) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
